﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using stirling_chillers.Models;

namespace stirling_chillers.Data
{
    /// <summary>
    /// 用户数据访问实现
    /// </summary>
    public class UserRepository : IUserRepository
    {
        private readonly string _connectionString;

        /// <summary>
        /// 构造函数注入数据库配置
        /// </summary>
        /// <param name="config">数据库配置</param>
        public UserRepository(MySqlConfig config)
        {
            _connectionString = config.ConnectionString;
        }

        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        public async Task<UserModel> GetUserByUsernameAsync(string username)
        {
            UserModel user = null;
            var sql = "SELECT  user_id,nick_name,user_name,identity_id,password,status,remark FROM  user_info WHERE user_name = @Username";

            using (var connection = new MySqlConnection(_connectionString))
            {
                await connection.OpenAsync();

                using (var command = new MySqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@Username", username);

                    using (var reader = await command.ExecuteReaderAsync())
                    {
                        if (await reader.ReadAsync())
                        {
                            user = new UserModel
                            {
                                UserId = reader.GetInt32("user_id"),
                                UserName = reader.GetString("user_name"),
                                Password = reader.GetString("password"),
                                NickName = reader.GetString("nick_name"),
                                IdentityId = reader.GetInt32("identity_id"),
                                Remark = reader.GetString("remark"),
                                Status = reader.GetInt32("status")
                            };
                        }
                    }
                }
            }
            return user;
        }
    }
}
